package com.glodon.paas.account.web.listener;

import com.glodon.paas.account.api.sso.web.AuthenticatedSessionRegistry;
import com.glodon.paas.account.api.sso.web.InMemoryAuthenticatedSessionRegistry;

import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

/**
 * @author Don Li
 */
public class AuthenticatedSessionServerListener implements HttpSessionAttributeListener {

    public static final String CAS_LOGIN_USER_ID = "cas-login-user-id";

    private static final AuthenticatedSessionRegistry registry = new InMemoryAuthenticatedSessionRegistry();

    /**
     * Invalidate all the sessions belong to the user
     *
     * @param id user id
     */
    public static void invalidateUserSessions(String id) {
        registry.invalidateUserSessions(id);
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent se) {
        if (getAttributeName().endsWith(se.getName())) {
            String userId = (String) se.getValue();
            registry.addSession(userId, se.getSession());
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent se) {
        if (getAttributeName().endsWith(se.getName())) {
            String userId = (String) se.getValue();
            registry.removeSession(userId, se.getSession());
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent se) {
        if (getAttributeName().endsWith(se.getName())) {
            String userId = (String) se.getValue();
            registry.addSession(userId, se.getSession());
        }
    }

    protected String getAttributeName() {
        return CAS_LOGIN_USER_ID;
    }
}
